<template>
  <div style="padding:20px">

    <!--  //查询条件-->
    <el-form :model="queryParams" :inline=true label-width="auto" style="max-width: 600px">
      <el-form-item label="品牌名称">
        <el-input v-model="queryParams.name" style="width: 240px" placeholder="请输入检索信息" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="iniPageData">搜索</el-button>
        <el-button type="Search" icon="Refresh" @click="handlerReset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-button icon="plus" type="primary" plain @click="handleShowSaveDialog">新增</el-button>
      <el-button icon="EditPen" type="success" plain>修改</el-button>
      <el-button icon="delete" type="danger" plain @click="handleBatchDel">删除</el-button>
    </el-row>
  </div>
    <!--    //分页列表展示-->
    <div>
      <el-table @selection-change="handleSelectChange" :data="brandList">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="品牌名称" prop="name" width="200"/>
        <el-table-column label="品牌图标" prop="logo" #default="scope">
          <img :src="scope.row.logo" width="50"/>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleShowUpdateDialog(scope.row)">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleShowRemove(scope.row.name,scope.row.id)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total=total
          v-model:page=queryParams.pageNum
          v-model:limit=queryParams.pageSize
          @pagination="iniPageData"
      />
    </div>
    <div>
    <!--// 新增、更新对话框-->
    <el-dialog v-model="dialogFormVisible" title="saveUpdateDialogTitle" width="500">
      <el-form>
        <el-form-item label="品牌名称" :label-width="formLabelWidth">
          <el-input v-model="newBrand.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="品牌logo">
          <el-upload
              class="avatar-uploader"
              :action="minioPath"
              :show-file-list="false"
              :headers="{'Authorization': 'Bearer ' + getToken()}"
              :on-success="handleAvatarSuccess"
          >
            <img v-if="newBrand.logo" :src="newBrand.logo" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="handleSaveOrUpdate">Confirm</el-button>
        </div>
      </template>
    </el-dialog>

  </div>

</template>

<script setup>
import {listBrand, saveBrand, getBrandDetails, deleteBrand,updateBrand} from '@/api/product/brand.js'
import {onMounted, reactive, ref} from 'vue'
import {getToken} from "@/utils/auth";
import {ElMessage, ElMessageBox} from "element-plus";
//初始化页面查询
onMounted(() => {
  iniPageData()
})
//重置
const handlerReset = () => {
  queryParams.value.name = null
  queryParams.value.pageNum = 1
  queryParams.value.pageSize = 3
  iniPageData()
}

//条件分页查询
const iniPageData = async () => {
  const {rows, total: t} = await listBrand(queryParams.value)
  brandList.value = rows;
  total.value = t;

}
//分页列表响应值
const brandList = ref([]);
const total = ref();
const queryParams = ref({
  pageNum: 1,
  pageSize: 3,
  name: null
})
//新增组件
//新增响应值
const newBrand = ref({})
const minioPath = "http://localhost:8080/file/upload"
const saveUpdateDialogTitle =ref("新增品牌")
//表单重置
function reset() {
  newBrand.value.name = null
  newBrand.value.logo = null
}

//上传图片成功回显
const handleAvatarSuccess =  (r) => {
  newBrand.value.logo = r.data.url
}
//增
//开对话框开关
const handleShowSaveDialog = () => {
  reset()
  saveUpdateDialogTitle.value="新增品牌"
  dialogFormVisible.value = true

}
//对话框开关
const dialogFormVisible = ref(false)
//提交表单
const saveNewBrand = async () => {
  await saveBrand(newBrand.value)
  iniPageData()
  ElMessage.success("新增成功")
  dialogFormVisible.value = false
}
//改
//改开关对话框
const handleShowUpdateDialog=async (row)=>{
  reset()
  saveUpdateDialogTitle.value="更新品牌"
  const {data} = await getBrandDetails(row.id)
  newBrand.value = data
  dialogFormVisible.value = true

}
const handleUpdate = async  ()=>{
  await updateBrand(newBrand.value)
  iniPageData()
  ElMessage.success('更新成功')
  dialogFormVisible.value = false
}
//新增、更新对话框 提交按钮的事件函数
const handleSaveOrUpdate = ()=> {
  if (newBrand.value.id) {
    //更新
    handleUpdate()
  } else {
    //新增
    saveNewBrand()
  }
}
//删
const handleShowRemove=(name,ids)=>{
  ElMessageBox.confirm(

          `正在删除品牌 ${name},是否继续?`,
          '删除确认',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(async () => {
            await deleteBrand(ids)
            ElMessage.success("删除成功")
            //刷新页面数据
            iniPageData();
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: '取消删除',
            })
          })

}
const handleBatchDel = () => {
  //1、判断是否选中了要删除的记录
  if (!selectRows.value || selectRows.value.length === 0) {
    ElMessage.warning('请选择要删除的行')
    return
  }
  //2、获取选中记录的id列表 拼接为 逗号分割的字符串
  let ids = selectRows.value.map(row => row.id).join(',')
  let names = selectRows.value.map(row => row.name).join('、')
  // console.log(ids)
  //3、调用上面的函数删除
  handleShowRemove(names, ids)}

const selectRows = ref([]) //接收选中要删除行的变量
const handleSelectChange = (newSelection) => {
  // console.log('表格选中行变化了：',newSelection)
  selectRows.value = newSelection;
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>